<template>
  <div class="map-selector">
    <div class="map-header">
      <h4>配送轨迹地图</h4>
      <div class="map-legend">
        <div class="legend-item">
          <span class="legend-color expected"></span>
          <span>预期路线</span>
        </div>
        <div class="legend-item">
          <span class="legend-color actual"></span>
          <span>实际路线</span>
        </div>
        <div class="legend-item">
          <span class="legend-color selectable"></span>
          <span>可选位置</span>
        </div>
      </div>
    </div>
    
    <div class="map-container">
      <div id="delivery-map" class="map"></div>
      <div v-if="loading" class="loading-overlay" v-loading="loading" element-loading-text="地图加载中...">
      </div>
    </div>
    
        <div class="map-instructions">
      <div class="instruction-card">
        <h5>📍 地图说明</h5>
        <ul>
          <li>🔵 蓝色虚线：起点到终点的预期路线</li>
          <li>🟠 橙色实线：基于实际轨迹的配送路径</li>
          <li>🟢 绿色标记：可选择的轨迹添加位置</li>
          <li>点击轨迹点查看详细信息和时间</li>
          <li>点击地图任意位置添加新的轨迹点</li>
        </ul>
      </div>
    </div>
    
    <div class="location-info">
      <div class="info-item">
        <label>选中坐标：</label>
        <span>{{ coordinates ? `${coordinates[0].toFixed(6)}, ${coordinates[1].toFixed(6)}` : '请在地图上点击选择位置' }}</span>
      </div>
    </div>
    
    <div class="map-actions">
      <el-button @click="handleCancel">取消</el-button>
      <el-button 
        type="info" 
        @click="copyCoordinates"
        :disabled="!coordinates"
      >
        复制坐标
      </el-button>
      <el-button 
        type="primary" 
        @click="handleConfirm" 
        :disabled="!selectedLocation"
      >
        确认选择
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted } from 'vue'
import { reverseGeocode } from '@/utils/geocoding'

interface LocationData {
  address: string
  coordinates: [number, number]
}

interface Props {
  orderData?: {
    senderAddress: string
    recipientAddress: string
    senderCoords?: [number, number]
    recipientCoords?: [number, number]
  }
  existingTracks?: Array<{
    coordinates?: [number, number]
    location: string
    timestamp: string
  }>
}

interface Emits {
  (e: 'locationSelected', data: LocationData): void
  (e: 'cancel'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const loading = ref(false)
const selectedLocation = ref('')
const coordinates = ref<[number, number] | null>(null)
const distanceFromStart = ref('')

let map: any = null
let marker: any = null
let expectedRoute: any = null
let actualRoute: any = null
let selectableMarkers: any[] = []
let isSelectingFromMarker = false // 标识是否正在从标记点选择

// 动态加载高德地图API
const loadAMapAPI = (): Promise<void> => {
  return new Promise((resolve, reject) => {
    if (typeof (window as any).AMap !== 'undefined') {
      resolve()
      return
    }

    const script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = 'https://webapi.amap.com/maps?v=1.4.15&key=a64438d3fab59804cee20ca25fa51f2a'
    script.async = true
    
    script.onload = () => {
      console.log('高德地图API加载成功')
      console.log('当前API版本:', (window as any).AMap?.version)
      console.log('可用服务:', Object.keys((window as any).AMap || {}))
      resolve()
    }
    
    script.onerror = (error) => {
      console.error('高德地图API加载失败:', error)
      reject(new Error('高德地图API加载失败'))
    }
    
    document.head.appendChild(script)
  })
}

// 初始化地图
const initMap = async () => {
  try {
    loading.value = true
    await loadAMapAPI()
    
    const container = document.getElementById('delivery-map')
    if (!container) {
      throw new Error('地图容器不存在')
    }

    const AMap = (window as any).AMap
    map = new AMap.Map('delivery-map', {
      zoom: 10,
      center: [116.397428, 39.90923],
      mapStyle: 'amap://styles/normal',
      zooms: [3, 20],
      dragEnable: true,
      zoomEnable: true,
      doubleClickZoom: true,
      keyboardEnable: true,
      scrollWheel: true,
      touchZoom: true,
      features: ['bg', 'point', 'road', 'building']
    })

    // 添加地图点击事件，允许用户在任意位置点击选择
    map.on('click', async (e: any) => {
      // 如果是从标记点触发的选择，则跳过地图点击处理
      if (isSelectingFromMarker) {
        isSelectingFromMarker = false
        return
      }
      
      const clickCoords: [number, number] = [e.lnglat.lng, e.lnglat.lat]
      await handlePointSelect(clickCoords)
    })

    // 初始化路线和轨迹
    if (props.orderData) {
      await initRoutes()
    } else {
      console.log('没有订单数据，跳过路线初始化')
    }
    
    console.log('配送地图初始化成功')
  } catch (error) {
    console.error('地图初始化失败:', error)
    initMockMap()
  } finally {
    loading.value = false
  }
}

// 绘制实际路线（基于已有轨迹）
const drawActualRoute = () => {
  if (!map || !props.existingTracks || props.existingTracks.length === 0) {
    console.log('没有现有轨迹数据，跳过实际路线绘制')
    return
  }

  const AMap = (window as any).AMap

  // 清除之前的实际路线
  if (actualRoute) {
    map.remove(actualRoute)
    actualRoute = null
  }

  // 过滤出有效的坐标点
  const validTracks = props.existingTracks.filter(track => 
    track.coordinates && 
    !isNaN(track.coordinates[0]) && 
    !isNaN(track.coordinates[1])
  ) as Array<{coordinates: [number, number], location: string, timestamp: string}>

  if (validTracks.length < 2) {
    console.log('有效轨迹点不足2个，无法绘制实际路线')
    return
  }

  // 按时间排序轨迹点
  validTracks.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime())

  const actualPath = validTracks.map(track => track.coordinates)
  console.log('绘制实际路线，轨迹点数量:', actualPath.length)

  // 绘制实际运输路线（橙色实线）
  actualRoute = new AMap.Polyline({
    path: actualPath,
    strokeColor: '#FF6B35',
    strokeWeight: 8,
    strokeStyle: 'solid',
    strokeOpacity: 1.0,
    zIndex: 100,
    showDir: true // 显示方向箭头
  })
  map.add(actualRoute)

  // 为轨迹点添加标记
  addTrackMarkers(validTracks)
}

// 添加轨迹点标记
const addTrackMarkers = (tracks: Array<{coordinates: [number, number], location: string, timestamp: string}>) => {
  const AMap = (window as any).AMap
  
  tracks.forEach((track, index) => {
    const isFirst = index === 0
    const isLast = index === tracks.length - 1
    
    let markerColor = '#FF6B35' // 橙色：中间轨迹点
    let markerText = (index + 1).toString()
    let markerSize = 28
    
    if (isFirst) {
      markerColor = '#1890FF' // 蓝色：起始轨迹点
      markerText = '始'
      markerSize = 32
    } else if (isLast) {
      markerColor = '#52C41A' // 绿色：最新轨迹点
      markerText = '新'
      markerSize = 32
    }

    const trackMarker = new AMap.Marker({
      position: track.coordinates,
      icon: new AMap.Icon({
        size: new AMap.Size(markerSize, markerSize),
        image: 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(`
          <svg xmlns="http://www.w3.org/2000/svg" width="${markerSize}" height="${markerSize}" viewBox="0 0 ${markerSize} ${markerSize}">
            <circle cx="${markerSize/2}" cy="${markerSize/2}" r="${markerSize/2 - 2}" fill="${markerColor}" stroke="white" stroke-width="2"/>
            <text x="${markerSize/2}" y="${markerSize/2 + 4}" text-anchor="middle" fill="white" font-size="${markerSize/3}" font-weight="bold">${markerText}</text>
          </svg>
        `),
        imageOffset: new AMap.Pixel(-markerSize/2, -markerSize/2)
      }),
      zIndex: 250,
      title: `轨迹点 ${index + 1}: ${track.location}\n时间: ${formatTrackTime(track.timestamp)}`
    })
    
    // 添加点击事件显示详细信息
    trackMarker.on('click', () => {
      const infoWindow = new AMap.InfoWindow({
        content: `
          <div style="padding: 12px; min-width: 200px;">
            <h4 style="margin: 0 0 8px 0; color: #1890FF;">轨迹详情 #${index + 1}</h4>
            <p style="margin: 4px 0;"><strong>位置:</strong> ${track.location}</p>
            <p style="margin: 4px 0;"><strong>时间:</strong> ${formatTrackTime(track.timestamp)}</p>
            <p style="margin: 4px 0;"><strong>坐标:</strong> ${track.coordinates[0].toFixed(6)}, ${track.coordinates[1].toFixed(6)}</p>
            <p style="margin: 4px 0; font-size: 12px; color: #666;">
              ${isFirst ? '🚀 配送起始点' : isLast ? '📍 最新位置' : '📌 中途轨迹点'}
            </p>
          </div>
        `,
        offset: new AMap.Pixel(0, -30)
      })
      infoWindow.open(map, track.coordinates)
    })
    
    map.add(trackMarker)
  })
}

// 格式化轨迹时间
const formatTrackTime = (timestamp: string): string => {
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 更新路线和轨迹（当props变化时调用）
const updateRoutes = () => {
  if (!map) return
  
  console.log('更新路线和轨迹显示')
  
  const AMap = (window as any).AMap
  
  // 重新绘制实际路线
  drawActualRoute()
  
  // 如果有实际轨迹，调整地图视野包含所有轨迹点
  if (props.existingTracks && props.existingTracks.length > 0) {
    const bounds = new AMap.Bounds()
    
    // 添加起点终点
    if (props.orderData?.senderCoords) {
      bounds.extend(new AMap.LngLat(props.orderData.senderCoords[0], props.orderData.senderCoords[1]))
    }
    if (props.orderData?.recipientCoords) {
      bounds.extend(new AMap.LngLat(props.orderData.recipientCoords[0], props.orderData.recipientCoords[1]))
    }
    
    // 添加所有轨迹点
    props.existingTracks.forEach(track => {
      if (track.coordinates) {
        bounds.extend(new AMap.LngLat(track.coordinates[0], track.coordinates[1]))
      }
    })
    
    map.setBounds(bounds, false, [30, 30, 30, 30])
  }
}

// 初始化路线和轨迹
const initRoutes = async () => {
  if (!map || !props.orderData) return
  
  const AMap = (window as any).AMap
  
  try {
    // 优先使用已有坐标，避免地址解析API调用
    let startCoords = props.orderData.senderCoords
    let endCoords = props.orderData.recipientCoords
    
    // 只有在没有坐标时才尝试地址解析，并且使用简化的备用方案
    if (!startCoords) {
      console.log('起点坐标不存在，使用地址智能匹配')
      startCoords = getCoordsByAddress(props.orderData.senderAddress)
    }
    
    if (!endCoords) {
      console.log('终点坐标不存在，使用地址智能匹配')
      endCoords = getCoordsByAddress(props.orderData.recipientAddress)
    }
    
    console.log('最终使用的坐标:', { startCoords, endCoords })
    
    // 添加起点和终点标记
    const startMarker = new AMap.Marker({
      position: startCoords,
      icon: new AMap.Icon({
        size: new AMap.Size(40, 40),
        image: 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(`
          <svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 40 40">
            <circle cx="20" cy="20" r="18" fill="#1890FF" stroke="white" stroke-width="3"/>
            <text x="20" y="26" text-anchor="middle" fill="white" font-size="14" font-weight="bold">起</text>
          </svg>
        `),
        imageOffset: new AMap.Pixel(-20, -20)
      }),
      zIndex: 300,
      title: '起点: ' + props.orderData.senderAddress
    })
    map.add(startMarker)
    
    const endMarker = new AMap.Marker({
      position: endCoords,
      icon: new AMap.Icon({
        size: new AMap.Size(40, 40),
        image: 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(`
          <svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 40 40">
            <circle cx="20" cy="20" r="18" fill="#52C41A" stroke="white" stroke-width="3"/>
            <text x="20" y="26" text-anchor="middle" fill="white" font-size="14" font-weight="bold">终</text>
          </svg>
        `),
        imageOffset: new AMap.Pixel(-20, -20)
      }),
      zIndex: 300,
      title: '终点: ' + props.orderData.recipientAddress
    })
    map.add(endMarker)
    
    // 绘制预期路线（起点到终点的虚线）
    expectedRoute = new AMap.Polyline({
      path: [startCoords, endCoords],
      strokeColor: '#1890FF',
      strokeWeight: 4,
      strokeStyle: 'dashed',
      strokeDasharray: [15, 10],
      strokeOpacity: 0.6,
      zIndex: 50
    })
    map.add(expectedRoute)
    console.log('预期路线绘制完成（起点到终点虚线）')
    
    // 绘制实际配送轨迹
    drawActualRoute()
    
    // 在预期路线上添加可选择的点（只有当起点终点不同时才添加）
    if (startCoords[0] !== endCoords[0] || startCoords[1] !== endCoords[1]) {
      await addSelectablePoints(startCoords, endCoords)
    } else {
      console.log('起点终点坐标相同，跳过可选择点生成')
    }
    
    // 调整地图视野
    updateRoutes()
    
  } catch (error) {
    console.error('初始化路线失败:', error)
  }
}

// 在预期路线上添加可选择的点
const addSelectablePoints = async (startCoords: [number, number], endCoords: [number, number]) => {
  const AMap = (window as any).AMap
  
  // 验证坐标有效性
  if (!startCoords || !endCoords || 
      isNaN(startCoords[0]) || isNaN(startCoords[1]) || 
      isNaN(endCoords[0]) || isNaN(endCoords[1])) {
    console.warn('坐标无效，跳过可选择点生成')
    return
  }
  
  // 在预期路线上生成若干个可选择的点
  const pointCount = 12 // 增加可选择的点数量
  
  for (let i = 1; i < pointCount - 1; i++) {
    const ratio = i / (pointCount - 1)
    const lng = startCoords[0] + (endCoords[0] - startCoords[0]) * ratio
    const lat = startCoords[1] + (endCoords[1] - startCoords[1]) * ratio
    
    // 验证计算出的坐标
    if (isNaN(lng) || isNaN(lat)) {
      console.warn(`跳过无效坐标点 ${i}: [${lng}, ${lat}]`)
      continue
    }
    
    const pointCoords: [number, number] = [lng, lat]
    
    const selectableMarker = new AMap.Marker({
      position: pointCoords,
      icon: new AMap.Icon({
        size: new AMap.Size(20, 20),
        image: 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(`
          <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20">
            <circle cx="10" cy="10" r="8" fill="#52C41A" stroke="white" stroke-width="2" opacity="0.9"/>
            <circle cx="10" cy="10" r="4" fill="white"/>
            <text x="10" y="13" text-anchor="middle" fill="#52C41A" font-size="8" font-weight="bold">${i}</text>
          </svg>
        `),
        imageOffset: new AMap.Pixel(-10, -10)
      }),
      zIndex: 200,
      cursor: 'pointer',
      title: `可选择位置 ${i} (点击选择)`
    })
    
    // 添加点击事件
    selectableMarker.on('click', async () => {
      // 设置标志位，防止触发地图点击事件
      isSelectingFromMarker = true
      await handlePointSelect(pointCoords)
    })
    
    // 添加鼠标悬停效果
    selectableMarker.on('mouseover', () => {
      selectableMarker.setIcon(new AMap.Icon({
        size: new AMap.Size(24, 24),
        image: 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(`
          <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
            <circle cx="12" cy="12" r="10" fill="#52C41A" stroke="white" stroke-width="2"/>
            <circle cx="12" cy="12" r="5" fill="white"/>
            <text x="12" y="16" text-anchor="middle" fill="#52C41A" font-size="10" font-weight="bold">${i}</text>
          </svg>
        `),
        imageOffset: new AMap.Pixel(-12, -12)
      }))
    })
    
    selectableMarker.on('mouseout', () => {
      selectableMarker.setIcon(new AMap.Icon({
        size: new AMap.Size(20, 20),
        image: 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(`
          <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20">
            <circle cx="10" cy="10" r="8" fill="#52C41A" stroke="white" stroke-width="2" opacity="0.9"/>
            <circle cx="10" cy="10" r="4" fill="white"/>
            <text x="10" y="13" text-anchor="middle" fill="#52C41A" font-size="8" font-weight="bold">${i}</text>
          </svg>
        `),
        imageOffset: new AMap.Pixel(-10, -10)
      }))
    })
    
    selectableMarkers.push(selectableMarker)
    map.add(selectableMarker)
  }
}

// 处理点击选择
const handlePointSelect = async (coords: [number, number]) => {
  const AMap = (window as any).AMap
  
  // 移除之前的选中标记
  if (marker) {
    map.remove(marker)
  }
  
  // 添加选中标记
  marker = new AMap.Marker({
    position: coords,
    icon: new AMap.Icon({
      size: new AMap.Size(24, 24),
      image: 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(`
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
          <circle cx="12" cy="12" r="10" fill="#FF4D4F" stroke="white" stroke-width="2"/>
          <circle cx="12" cy="12" r="6" fill="white"/>
          <circle cx="12" cy="12" r="3" fill="#FF4D4F"/>
        </svg>
      `),
      imageOffset: new AMap.Pixel(-12, -12)
    }),
    zIndex: 300
  })
  map.add(marker)
  
  // 设置坐标信息
  coordinates.value = coords
  
  try {
    // 使用逆地理编码获取地址
    const address = await reverseGeocode(coords[0], coords[1])
    selectedLocation.value = address
    console.log('选中位置:', address, '坐标:', coords)
  } catch (error) {
    console.warn('逆地理编码失败，使用坐标显示:', error)
    selectedLocation.value = `坐标位置 (${coords[0].toFixed(6)}, ${coords[1].toFixed(6)})`
  }
  
  // 简化距离显示
  distanceFromStart.value = '位置信息已记录'
}

// 简化的地址坐标匹配（避免API调用）
const getCoordsByAddress = (address: string): [number, number] => {
  if (!address) {
    return [113.2644, 23.1291] // 默认广州
  }
  
  // 基于地址关键词的智能匹配，避免API调用
  const cityCoords: Record<string, [number, number]> = {
    '北京': [116.4074, 39.9042],
    '上海': [121.4737, 31.2304],
    '广州': [113.2644, 23.1291],
    '深圳': [114.0579, 22.5431],
    '杭州': [120.1551, 30.2741],
    '南京': [118.7969, 32.0603],
    '武汉': [114.3054, 30.5931],
    '成都': [104.0665, 30.5723],
    '西安': [108.9398, 34.3416],
    '重庆': [106.5516, 29.5630],
    '天津': [117.2008, 39.0842],
    '苏州': [120.6197, 31.3003],
    '青岛': [120.3826, 36.0671],
    '大连': [121.6147, 38.9140],
    '宁波': [121.5440, 29.8683],
    '厦门': [118.0894, 24.4798],
    '福州': [119.2965, 26.0745],
    '济南': [117.1205, 36.6519],
    '郑州': [113.6254, 34.7466],
    '长沙': [112.9388, 28.2282],
    '南昌': [115.8921, 28.6765],
    '合肥': [117.2272, 31.8206],
    '石家庄': [114.5149, 38.0428],
    '太原': [112.5489, 37.8706],
    '沈阳': [123.4315, 41.8057],
    '长春': [125.3235, 43.8171],
    '哈尔滨': [126.5358, 45.8023],
    '昆明': [102.8329, 24.8801],
    '贵阳': [106.6302, 26.6477],
    '南宁': [108.3669, 22.8170],
    '海口': [110.3312, 20.0311],
    '兰州': [103.8236, 36.0581],
    '西宁': [101.7782, 36.6171],
    '银川': [106.2309, 38.4872],
    '乌鲁木齐': [87.6177, 43.7928],
    '拉萨': [91.1409, 29.6456]
  }
  
  // 尝试匹配城市名称
  for (const [city, coords] of Object.entries(cityCoords)) {
    if (address.includes(city)) {
      console.log(`地址智能匹配: ${address} -> ${city} [${coords[0]}, ${coords[1]}]`)
      return coords
    }
  }
  
  // 按省份匹配
  const provinceCoords: Record<string, [number, number]> = {
    '广东': [113.2644, 23.1291],
    '江苏': [118.7969, 32.0603],
    '浙江': [120.1551, 30.2741],
    '山东': [117.1205, 36.6519],
    '河南': [113.6254, 34.7466],
    '湖北': [114.3054, 30.5931],
    '湖南': [112.9388, 28.2282],
    '四川': [104.0665, 30.5723],
    '福建': [119.2965, 26.0745],
    '河北': [114.5149, 38.0428],
    '安徽': [117.2272, 31.8206],
    '江西': [115.8921, 28.6765],
    '山西': [112.5489, 37.8706],
    '辽宁': [123.4315, 41.8057],
    '吉林': [125.3235, 43.8171],
    '黑龙江': [126.5358, 45.8023],
    '陕西': [108.9398, 34.3416],
    '甘肃': [103.8236, 36.0581],
    '青海': [101.7782, 36.6171],
    '宁夏': [106.2309, 38.4872],
    '新疆': [87.6177, 43.7928],
    '西藏': [91.1409, 29.6456],
    '云南': [102.8329, 24.8801],
    '贵州': [106.6302, 26.6477],
    '广西': [108.3669, 22.8170],
    '海南': [110.3312, 20.0311],
    '内蒙古': [111.7522, 40.8517]
  }
  
  for (const [province, coords] of Object.entries(provinceCoords)) {
    if (address.includes(province)) {
      console.log(`地址智能匹配: ${address} -> ${province}省 [${coords[0]}, ${coords[1]}]`)
      return coords
    }
  }
  
  console.log(`地址智能匹配: ${address} -> 使用默认坐标（广州）`)
  return [113.2644, 23.1291] // 默认返回广州坐标
}

// 注意：已移除复杂的地址解析和驾车路线规划功能
// 现在使用简化的坐标处理，地址转换交给后端

// 模拟地图（用于开发测试）
const initMockMap = () => {
  const mapElement = document.getElementById('delivery-map')
  if (mapElement) {
    mapElement.innerHTML = `
      <div style="
        height: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border: 2px dashed #d9d9d9;
        color: white;
        font-size: 16px;
        cursor: pointer;
        text-align: center;
        padding: 20px;
        box-sizing: border-box;
      " onclick="handleMockMapClick()">
        <div style="font-size: 48px; margin-bottom: 16px;">🗺️</div>
        <div style="font-size: 18px; font-weight: bold; margin-bottom: 8px;">地图服务暂时不可用</div>
        <div style="font-size: 14px; margin-bottom: 16px;">API密钥配置问题，使用模拟地图</div>
        <div style="
          background: rgba(255,255,255,0.2);
          padding: 12px 24px;
          border-radius: 6px;
          border: 1px solid rgba(255,255,255,0.3);
          cursor: pointer;
          transition: all 0.3s;
        " onmouseover="this.style.background='rgba(255,255,255,0.3)'" 
           onmouseout="this.style.background='rgba(255,255,255,0.2)'">
          点击选择默认位置
        </div>
        <small style="font-size: 12px; margin-top: 16px; opacity: 0.8;">
          配送员可以继续进行轨迹添加操作
        </small>
      </div>
    `
    
    // 添加全局方法供模拟地图调用
    ;(window as any).handleMockMapClick = async () => {
      // 根据订单地址智能选择默认位置
      let defaultLocation = '广东省广州市天河区'
      let defaultCoords: [number, number] = [113.2644, 23.1291]
      
      if (props.orderData?.recipientAddress) {
        const address = props.orderData.recipientAddress
        if (address.includes('北京')) {
          defaultLocation = '北京市朝阳区'
          defaultCoords = [116.4074, 39.9042]
        } else if (address.includes('上海')) {
          defaultLocation = '上海市黄浦区'
          defaultCoords = [121.4737, 31.2304]
        } else if (address.includes('广州') || address.includes('广东')) {
          defaultLocation = '广东省广州市天河区'
          defaultCoords = [113.2644, 23.1291]
        } else if (address.includes('深圳')) {
          defaultLocation = '广东省深圳市南山区'
          defaultCoords = [114.0579, 22.5431]
        }
      }
      
      coordinates.value = defaultCoords
      
      try {
        // 尝试获取更精确的地址
        const address = await reverseGeocode(defaultCoords[0], defaultCoords[1])
        selectedLocation.value = address
      } catch (error) {
        selectedLocation.value = `${defaultLocation}（模拟位置）`
      }
      
      console.log('🎯 模拟地图选择位置:', selectedLocation.value, coordinates.value)
    }
  }
}

// 已移除复杂的地址解析功能，现在只处理坐标信息

// 在组件挂载后初始化
onMounted(() => {
  // 延迟初始化，确保DOM已渲染
  setTimeout(async () => {
    try {
      await initMap()
      console.log('地图初始化完成')
    } catch (error) {
      console.error('地图初始化失败，使用模拟地图:', error)
    }
  }, 100)
})

// 复制坐标到剪贴板
const copyCoordinates = async () => {
  if (!coordinates.value) return
  
  const coordText = `${coordinates.value[0].toFixed(6)}, ${coordinates.value[1].toFixed(6)}`
  try {
    await navigator.clipboard.writeText(coordText)
    console.log('坐标已复制到剪贴板:', coordText)
    // 可以添加一个简单的提示
    selectedLocation.value = `坐标已复制: ${coordText}`
    setTimeout(() => {
      selectedLocation.value = `坐标位置 (${coordinates.value![0].toFixed(6)}, ${coordinates.value![1].toFixed(6)})`
    }, 2000)
  } catch (error) {
    console.warn('复制坐标失败:', error)
    selectedLocation.value = `复制失败，坐标: ${coordText}`
  }
}

const handleConfirm = () => {
  if (coordinates.value && selectedLocation.value) {
    // 只传递地址信息，不传递坐标
    emit('locationSelected', {
      address: selectedLocation.value,
      coordinates: coordinates.value // 保留坐标用于前端显示，但不传给后端
    })
    console.log('确认选择地址:', selectedLocation.value)
  }
}

const handleCancel = () => {
  emit('cancel')
}

// 监听props变化，重新初始化路线
watch(() => [props.orderData, props.existingTracks], async () => {
  if (map && props.orderData) {
    // 清理现有的路线和标记
    if (expectedRoute) {
      map.remove(expectedRoute)
      expectedRoute = null
    }
    if (actualRoute) {
      map.remove(actualRoute)
      actualRoute = null
    }
    selectableMarkers.forEach(marker => map.remove(marker))
    selectableMarkers.length = 0
    
    // 重新初始化路线
    await initRoutes()
  }
}, { deep: true })

// 移除重复的onMounted

onUnmounted(() => {
  if (map) {
    map.destroy()
  }
  // 清理全局方法
  if ((window as any).handleMockMapClick) {
    delete (window as any).handleMockMapClick
  }
})
</script>

<style scoped>
.map-selector {
  display: flex;
  flex-direction: column;
  height: 600px;
  gap: 16px;
}

.map-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 4px;
}

.map-header h4 {
  margin: 0;
  font-size: 16px;
  color: #303133;
  font-weight: 600;
}

.map-legend {
  display: flex;
  gap: 16px;
  align-items: center;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #606266;
}

.legend-color {
  width: 16px;
  height: 3px;
  border-radius: 2px;
}

.legend-color.expected {
  background: #1890FF;
  border: 1px dashed #1890FF;
}

.legend-color.actual {
  background: #FF6B35;
}

.legend-color.selectable {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background: #52C41A;
  border: 2px solid white;
}

.map-container {
  flex: 1;
  position: relative;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  overflow: hidden;
  min-height: 400px;
}

.map {
  width: 100%;
  height: 100%;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.8);
  z-index: 1000;
}

.location-info {
  padding: 16px;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-item label {
  font-weight: 600;
  color: #495057;
  width: 90px;
  flex-shrink: 0;
  font-size: 13px;
}

.info-item span {
  color: #212529;
  flex: 1;
  font-size: 13px;
}

.status-success {
  color: #67C23A !important;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 4px;
}

.map-instructions {
  margin-bottom: 16px;
}

.instruction-card {
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  border: 1px solid #0ea5e9;
  border-radius: 8px;
  padding: 16px;
}

.instruction-card h5 {
  margin: 0 0 12px 0;
  color: #0369a1;
  font-size: 14px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.instruction-card ul {
  margin: 0;
  padding-left: 16px;
  color: #0f172a;
}

.instruction-card li {
  margin-bottom: 6px;
  font-size: 13px;
  line-height: 1.4;
}

.instruction-card li:last-child {
  margin-bottom: 0;
}

.map-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 16px;
  border-top: 1px solid #e9ecef;
}

@media (max-width: 768px) {
  .map-selector {
    height: 500px;
  }
  
  .map-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .map-legend {
    gap: 12px;
  }
  
  .info-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .info-item label {
    width: auto;
  }
}
</style>